package A9_JUC辅助类;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 *
 *  裁判员发令枪响，运动员跑步，结束统计排名
 * @Author: KingWang
 * @Date: 2021/5/23
 * @Desc:
 **/
public class CountDownLatchDemo2 {

    public static void main(String[] args) {
        CountDownLatch countDownLatchOne = new CountDownLatch(1); //等待裁判发令枪响
        CountDownLatch countDownLatchTwo = new CountDownLatch(10); //等待运动员跑步

        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                try {
                    countDownLatchOne.await();  //等待发令枪响
                    System.out.println(Thread.currentThread().getName() + "号\t 运动员开始起跑");
                    int runtime = new Random().nextInt(9) + 1;
                    TimeUnit.SECONDS.sleep(runtime);
                    System.out.println(Thread.currentThread().getName() +  "号\t 运动员到达终点,时间" + runtime + "秒");
                    countDownLatchTwo.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }

        //倒计时10秒
        try{


        System.out.println("开始进入倒计时3秒");
        TimeUnit.SECONDS.sleep(3);
        System.out.println("裁判开发令枪，比赛开始");
        countDownLatchOne.countDown();
        countDownLatchTwo.await();
        System.out.println("比赛结束");
        } catch (Exception e){
            e.printStackTrace();
        }



    }
}
